<template>
  <div style="padding: 1.25rem">
    <!-- 对话框 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" :rules="rules" ref="form1" label-width="70px">
        <slot name="form"></slot>
        <el-form-item class="" v-if="fileButt1" label="图片">
          <el-upload   drag action="qwer" :before-upload="beforeupload" :on-change="fileChange">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save" :disabled="saveBtnDisable">保存</el-button>
      </span>
    </el-dialog>
    <!-- 图片弹框 -->
    <el-dialog title="图片" :visible.sync="photo" width="500px">
      <el-image style="width: 360px;" :src="phoUrl">
      </el-image>
    </el-dialog>
    <p>
      <el-row>
        <el-col :span="20">
          <el-button :size="size" type="info" icon="el-icon-plus" @click="addClick">新增</el-button>
          <el-button :size="size" type="info" icon="el-icon-edit" @click="editClick" :disabled="!currentRow">修改</el-button>
          <el-button :size="size" type="info" icon="el-icon-delete" @click="delClick" :disabled="!currentRow">删除</el-button>
          <slot name="buttons"></slot>
          
          <el-button v-if="fileButt1" :size="size" type="info" icon="el-icon-user" @click="photo1" :disabled="!currentRow">查看照片</el-button>
          <el-button v-if="fileButt1" :size="size" type="info" icon="el-icon-postcard" @click="czmm" :disabled="!currentRow">重置密码</el-button>
          <el-button type="warning" :size="size" icon="el-icon-refresh" @click="refreshTable">刷新</el-button>

        </el-col>
        <el-col :span="4">
          <el-input :size="size" placeholder="请输入查询内容" prefix-icon="el-icon-search" v-model="queryParams.search"
            @change="searChange" clearable />
        </el-col>
      </el-row>
    </p>
    <el-table  height="55vh" :size="size" :data="stus" v-bind="tableAttrs" highlight-current-row @current-change="currentChange" style="width: 100%">
      <el-table-column v-for="(item,index) in cols" :key="index" :property="item.property" :label="item.label">
      </el-table-column>
    </el-table>
    <div style="margin-top: 0.625rem;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryParams.page"
        :page-sizes="pageSizes" :page-size="queryParams.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'myTable',
    //组件属性
    props: {
      size: {
        type: String,
        default: 'small',
      },
      add: {
        type: Boolean,
        default: true,
      },
      edit: {
        type: Boolean,
        default: true,
      },
      del: {
        type: Boolean,
        default: true,
      },
      refresh: {
        type: Boolean,
        default: true
      },
      url: {
        type: String,
        default: 'page'
      },
      deleteUrl: {
        type: String,
        default: 'delete'
      },
      saveUrl: {
        type: String,
        default: 'save',
      },
      path: {
        type: String,
      },
      formObj: {
        type: Object,
        default: () => {}
      },
      cols: {
        type: Array,
        required: true,
      },
      tableData: {
        type: Array,
      },
      rules: {
        type: Object,
        default: () => {}
      },
      pageParams: {
        type: Object,
      },
      pageSize: {
        type: Array,
        default: () => [10, 20, 30, 50]
      },
      tableAttrs: {
        type: Object,
        default: () => {}
      },
      urlParam: {
        type: Object,
        default: () => {}
      },
      param: {
        type: Object,
        default: () => {}
      },
      fileButt: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        dialogVisible: false,
        title: '对话框',
        fileButt1: false,
        //size: 'small',
        stus: [],
        total: 0,
        param: {
          file: '',
        },
        ajaxUrl: {
          url: '',
          deleteUrl: '',
          saveUrl: '',
        },
        form: {

        },
        phoUrl: '',
        photo: false,
        saveBtnDisable: false,
        currentRow: null,
        queryParams: {
          limit: 10,
          page: 1,
          sort: 'id',
          order: 'asc',
          search: ''
        },
        pageSizes: [10, 20, 30, 50],
      }
    },
    methods: {
      beforeupload(file) {
        this.param.file = file
        console.log(this.param)
        return false;
      },
      //照片大小
      fileChange(file, oldFile) {
        let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
        oldFile = [];
        if (fileType !== 'jpeg' && fileType !== 'jpg' && fileType !== 'png') {
          this.$message.error("头像格式不正确");
          return false;
        }
        if (file.size / 1024 / 1024 > 1.5) {
          this.$message.error("头像大小不能超过2M");
          return false;
        }
        this.file = file.raw;
      },
      //重置密码
      czmm() {
        this.$confirm('是否重置密码为1111?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$ajax.post('student/resetPwd', this.currentRow).then(res => {
            this.refreshtable();
            this.$notify({
              type: 'success',
              message: '重置成功!',
              position: 'bottom-right'
            });
          })
        }).catch(() => {
          this.$notify({
            type: 'success',
            message: '取消重置',
            position: 'bottom-right',
            type: 'info'
          });
        });
      },
      //显示照片
      photo1() {
        this.phoUrl = this.baseURL + "student/download?id=" + this.currentRow.id;
        this.photo = true;

      },
      //新增方法
      addClick() {
        this.param = {};
        emptyObj(this.form);
        this.$emit('show-dialog', this.form);
        this.dialogVisible = true;
      },
      //修改方法
      editClick() {
        this.param = {};
        Object.assign(this.form, this.currentRow);
        this.$emit('show-dialog', this.form);
        this.dialogVisible = true;
      },
      //删除方法
      delClick() {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          this.$ajax.post(this.ajaxUrl.deleteUrl, this.currentRow).then(res => {
            var result = res.data;
            if (result.success) {
              this.$notify.success({
                title: '提示',
                message: '数据删除成功',
                position: 'bottom-right',
              });
              this.total--;
              this.$emit('deleted', this.currentRow);
              this.refreshTable();
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: '删除失败'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //保存
      save() {
        this.$refs.form1.validate(valid => {
          if (valid) {
            this.$ajax.post(this.ajaxUrl.saveUrl, Object.assign({}, this.param, this.form, this.urlParam)).then(res => {
              var result = res.data;
              if (result.success) {
                this.dialogVisible = false;
                this.$notify({
                  title: '提示',
                  message: '数据保存成功',
                  position: 'bottom-right'
                });
                this.$emit('save-succ', this.form);
                this.refreshTable();
              } else {
                this.$message({
                  message: res.msg,
                  type: 'warning'
                });
              }
            }).catch(error => {
              this.dialogVisible = false
              this.$message({
                message: '用户名重复',
                type: 'warning'
              })

            })
          }
        })
      },
      //选中行
      currentChange(row) {
        this.currentRow = row;
      },
      //刷新
      refreshTable() {
        if (this.queryParams.limit * (this.queryParams.page - 1) >= this.total && this.queryParams.page > 1) {
          this.queryParams.page--;
        }
        this.$ajax.post(this.ajaxUrl.url, Object.assign({}, this.queryParams, this.urlParam)).then(res => {
          var result = res.data;
          if (result.success) {
            // this.stus = result.data;
            this.stus = result.data.rows;
            this.total = result.data.total;
            this.currentRow = null;
          }
        }).catch(err => {})
      },
      //分页每页数
      handleSizeChange(val) {
        //console.log(`每页 ${val} 条`);
        this.queryParams.limit = val;
        this.refreshTable();
      },
      //分页当前页数
      handleCurrentChange(val) {
        //console.log(`当前页: ${val}`);
        this.queryParams.page = val;
        this.refreshTable();
      },
      searChange() {
        this.queryParams.page = 1;
        this.refreshTable();
      }
    },
    mounted() {
      this.refreshTable();
    },
    //页面传值路径
    created() {
      this.fileButt1 = this.fileButt;
      if (this.path) {
        this.ajaxUrl.url = this.path + this.url;
        this.ajaxUrl.deleteUrl = this.path + this.deleteUrl;
        this.ajaxUrl.saveUrl = this.path + this.saveUrl;
      } else {
        this.ajaxUrl.url = this.url;
        this.ajaxUrl.deleteUrl = this.deleteUrl;
        this.ajaxUrl.saveUrl = this.saveUrl;
      }
      this.form = this.formObj;
      Object.assign(this.queryParams, this.pageParams);
      this.pageSizes = this.pageSize;
    }
  }

  function emptyObj(obj) {
    for (var key in obj) {
      var o = obj[key];
      if (o instanceof Object) {
        emptyObj(o);
      } else {
        obj[key] = '';
      }
    }
  }
</script>

<style scoped>

</style>
